//
//  SimpleActionSheetView.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 17/1/3.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "SimpleActionSheetView.h"
#import "XUIPanelWindow.h"
#import "SimpleAcionSheetCell.h"

#define CellHeight 60
#define MaxCellCount 3

@interface SimpleActionSheetView()<XUIGroupTableViewDelegate,XUIGroupTableViewDataSource,UIGestureRecognizerDelegate>
{
    XUIPanelWindow *_window;
    
    NSString *_title;
    NSArray *_data;
    
    id<SimpleActionSheetViewDelegate> _delegate;
    
    XUIGroupTableView *_gtable;
}
@end

@implementation SimpleActionSheetView

- (id)initWithTitle:(NSString *)title data:(NSArray *)data delegate:(id<SimpleActionSheetViewDelegate>)delegate
{
    self = [super initWithFrame:CGRectZero];
    self.backgroundColor = [UIColor colorWithR:0 G:0 B:0 A:0.6];
    
    _title = title;
    _data = [data mutableCopy];
    _delegate = delegate;
    
    [self initVariable];
    [self initUI];
    
    return self;
}

- (void)initVariable
{
    [self addMainThreadObserverWithDictionarySelector:@{XLGHeadImageDownloadQueueHeadImageDownloadResultNotification:@"observerHeadImageDownloadQueueHeadImageDownloadResultNotification:"}];
}

+(void)actionSheetViewWithTitle:(NSString *)title data:(NSArray *)data delegate:(id<SimpleActionSheetViewDelegate>)delegate
{
    SimpleActionSheetView *view = [[SimpleActionSheetView alloc]initWithTitle:title data:data delegate:delegate];
    
    [view show];
}

-(void)layoutSubviews
{
    [super layoutSubviews];
}

- (void)show
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    _window = [XUIPanelWindow new];
    _window.responder = self;
    
    self.frame = _window.bounds;
    
    NSInteger count = MaxCellCount;
    CGFloat height = count * CellHeight;
    if(_data.count < count)
    {
        height = _data.count * CellHeight;
    }
    _gtable.frame = CGRectMake(0, 0, self.width, height);
    
    self.alpha = 0;
    _gtable.top = self.height;
    
    keyWindow.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.3 animations:^
     {
         _gtable.bottom = self.height;
         self.alpha = 1;
         
     } completion:^(BOOL finished)
     {
         keyWindow.userInteractionEnabled = YES;
     }];
}

- (void)initUI
{
    _gtable = [[XUIGroupTableView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
    _gtable.backgroundColor = [UIColor colorWithR:227 G:227 B:227 A:1];
    _gtable.delegate = self;
    _gtable.dataSource = self;
    
    [self addSubview:_gtable];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
    tap.delegate = self;
    [self addGestureRecognizer:tap];
}

#pragma mark --
#pragma mark -- groupTableView delegate

- (NSUInteger)numberOfGroupsInGroupTableView:(XUIGroupTableView *)groupTableView
{
    return 1;
}

- (NSUInteger)groupTableView:(XUIGroupTableView *)groupTableView numberOfRowsInGroup:(NSInteger)group
{
    return _data.count;
}

-(CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForHeaderInGroup:(NSInteger)group
{
    return 0;
}

- (CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CellHeight;
}

- (XUIGroupTableViewCell *)groupTableView:(XUIGroupTableView *)groupTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SimpleAcionSheetCell *cell = [[SimpleAcionSheetCell alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    SimpleActionSheetInfo *info = [_data objectAtIndex:indexPath.row];
    
    UIImage *headImage = nil;
    if(info.icon.length >0)
    {
        if([info.icon rangeOfString:ServiceDefaultHeadImageTag].location == NSNotFound)
        {
            XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue checkOrStartDownloadHeadImageWhenAddHeadImageURL:info.icon forKey:XLGHeadImageDownloadQueueSysIcon];
            if(cache != nil)
                headImage = cache;
            else
                headImage = [UIImage imageNamed:@"img_defaulthead.png"];
        }
        else
        {
            NSString *h = [info.icon substringFromIndex:[info.icon rangeOfString:ServiceDefaultHeadImageTag].length];
            headImage = [UIImage imageNamed:h];
        }
    }
    else
        headImage = [UIImage imageNamed:@"img_defaulthead.png"];
    
    headImage = [UIImage resizeImage:headImage withNewSize:CGSizeMake(100, 100)];
    
    cell.headImage = headImage;
    cell.title = info.name;
    cell.szTag = info.dataId;
    
    return cell;
}

- (void)groupTableView:(XUIGroupTableView *)groupTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([_delegate respondsToSelector:@selector(actionSheetView:didSelectRowAtIndexPath:)])
    {
        [_delegate actionSheetView:self didSelectRowAtIndexPath:indexPath];
        
        [self close];
    }
}

-(void)close
{
    self.superview.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.3 animations:^
     {
         self.top = [self superview].bottom;
         self.alpha = 0;
         
     } completion:^(BOOL finished)
     {
         self.superview.userInteractionEnabled = YES;
         
         [self removeFromSuperview];
         
         _window = nil;
     }];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    CGPoint p = [touch locationInView:self];
    if (CGRectContainsPoint(_gtable.frame, p) == YES)
        return NO;
    return YES;
}

- (void)tapGestureRecognizer:(UITapGestureRecognizer *)gr
{
    if([_delegate respondsToSelector:@selector(willDismissActionSheetView:)])
        [_delegate willDismissActionSheetView:self];
    [self close];
}

#pragma mark --
#pragma mark -- refresh headImage
-(void)observerHeadImageDownloadQueueHeadImageDownloadResultNotification:(NSNotification*)noti
{
    NSString *path =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultPathKey];
    NSString *URL =[noti.userInfo objectForKey:XLGHeadImageDownloadQueueHeadImageDownloadResultURLKey];
    
    for (SimpleActionSheetInfo *info in _data)
    {
        if([info.icon isEqualToString:URL])
        {
            XLGHeadImageCache *cache = [XLGHeadImageDownloadQueue setCacheWithHeadImageURL:URL andHeadImagePath:path forKey:XLGHeadImageDownloadQueueSysIcon];
                    
            UIImage *headImage = (UIImage*)cache;
            headImage = [UIImage resizeImage:headImage withNewSize:CGSizeMake(100, 100)];
                    
            SimpleAcionSheetCell *cell = (SimpleAcionSheetCell*)[_gtable cellWithTag:info.dataId];
            cell.headImage = headImage;
        }
    }
}
@end
